package com.siyoumi.validator;

import com.siyoumi.validator.annotation.EqualsValues;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;
import org.hibernate.validator.internal.engine.path.PathImpl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.ValidationException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class EqualsValuesValidator
        implements ConstraintValidator<EqualsValues, Object> {
    EqualsValues annotation;

    @Override
    public void initialize(EqualsValues constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);

        this.annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object o, ConstraintValidatorContext context) {
        String s = "";
        if (o instanceof String) {
            s = (String) o;
            log.debug("s: {}", s);
        } else if (o instanceof Integer) {
            s = ((Integer) o).toString();
        } else {
            return true;
        }

        Map<String, String> map = new HashMap<>();
        map.put("{vals}", Arrays.toString(annotation.vals()));
        XValidator.addValidatorMessageParame(context, map);

        String ss = s;
        List<String> vals = Arrays.asList(annotation.vals());
        return vals.stream().anyMatch(v -> v.equals(ss));
    }
}
